package java8;

import java.io.FileReader;

/*since1.7*/
public class AutoCloseableTest {

    public static void main(String[] args) {
        autoCLose();
    }

    private static void autoCLose() {
        /*示例一、系统api*/
        try (FileReader reader = new FileReader("")) {
            int read = reader.read();
        } catch (Exception e) {
            System.out.println("reader exception:" + e);
        }

        /*示例二、自定义*/
        try (Resource resource = new Resource(0x01)) {
            int id = resource.getId();
            //int v = 1 / 0;
            System.out.println("id is:" + id);
        } catch (Exception e) {
            System.out.println("catch:" + e.toString());
        } finally {
            System.out.println("finally()");
        }
    }


    private static class Resource implements AutoCloseable {
        private final int id;

        public Resource(int id) {
            this.id = id;
        }

        public int getId() {
            return id;
        }

        @Override
        public void close() throws Exception {
            System.out.println("resource instance has been closed");
        }
    }
}
